﻿using BaseFramework;
using BaseFramework.DbConnectionProvider;
using LiteFramework.Contract;
using LiteFramework.Model;
using System;

namespace LiteFramework.Server.Component
{
    public class UserComponent : AbsComponent<User>, IUserContract
    {
        public UserComponent(IDbConnectionProvider connectionProvider = null)
            : base(connectionProvider)
        {
        }

        [AccessSecurity(System.Security.Permissions.SecurityAction.Demand)]
        protected override void check_TaskRight_Get()
        {
            base.check_TaskRight_Get();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="isOnline">如果为 true，则更新指定用户的最近活动日期/时间戳。</param>
        /// <returns></returns>
        public User GetUser(bool isOnline = false)
        {
            User user = null;
            if (ServerApplication.Current.TrueUser != null)
            {
                IReIsolatedCache cache = ServerApplication.Cache;
                object obj = cache.IsolatedGet(ServerApplication.Current.TrueUser.ProviderUserKey);

                if (obj != null)
                {
                    return (User)obj;
                }
                else
                {
                    user = this.Get(ServerApplication.Current.TrueUser.ID);
                    if (user != null)
                    {
                        user.Roles = ServerApplication.ComponentFactory.Create<RoleComponent>().GetUserRoles(user.ID);

                        if (user.IsOnline)
                        {
                            cache.IsolatedAdd(user.ProviderUserKey, user);
                        }

                        return user;
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="isOnline">如果为 true，则更新指定用户的最近活动日期/时间戳。</param>
        /// <returns></returns>
        public User GetUser(string userName, bool isOnline = false)
        {
            if (isOnline)
            {
                var onlineTime = DateTime.Now;
                var sql = "UPDATE SYS_User SET LastActivityTime=@LastActivityTime WHERE UserName=@UserName"; // 更新在线时间
                var param = new System.Data.IDbDataParameter[] { 
                this.SqlHelper.CreateParameter("UserName", userName), 
                this.SqlHelper.CreateParameter("LastActivityTime", onlineTime) };
                this.SqlHelper.ExecNonQuery(sql, param);
            }

            return this.FindOne(Expression.Eq("UserName", userName));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="openId"></param>
        /// <param name="isOnline">如果为 true，则更新指定用户的最近活动日期/时间戳。</param>
        /// <returns></returns>
        public User GetUserByOpenId(LoginType type, string openId, bool isOnline)
        {
            User user = null;

            if (user != null && isOnline)
            {
                this.AddUserToCache(user);
            }

            return user;
        }

        /// <summary>
        /// 发送活动心跳信号。指示当前用户状态为【在线活动】，必要时可以调用此方法以避免用户长时间未操作数据导致的登陆超时问题
        /// </summary>
        public bool HeartBeat()
        {
            return this.GetUser(true) != null;
        }

        internal void AddUserToCache(User user)
        {
            ServerApplication.Cache.IsolatedAdd(user.ProviderUserKey, user);
        }
        internal void RemoveUserFromCache(User user)
        {
            ServerApplication.Cache.IsolatedRemove(user.ProviderUserKey);
        }

        internal bool AdditionalAuthenticate(User user, object State)
        {
            return true;
        }
    }
}